package com.seata.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seata.core.exception.BusinessException;
import com.seata.core.support.LogSupport;
import com.seata.storage.dao.entity.Storage;
import com.seata.storage.dao.mapper.StorageMapper;
import com.seata.storage.service.StorageService;

import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 *
 */
@Service("storageService")
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService {

    @Override
    public boolean decrease(Long productId, Integer count) throws BusinessException, InterruptedException {
        // 查询库存是否存在
        QueryWrapper<Storage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Storage::getProductId, productId);
        Storage storage = this.getOne(queryWrapper);
        if (Objects.isNull(storage)) {
            throw new BusinessException("库存信息不存在");
        }
        LogSupport.logInfo("扣减库存, commit, productId:{}, count:{}", productId, count);
        getBaseMapper().decrease(productId, count);
        if (count == 3) {
            Thread.sleep(3000L);
            throw new BusinessException("库存信息异常");
        }
        //throw new RuntimeException();
        return true;
    }

    @Override
    public boolean compensateDecrease(Long productId, Integer count) throws BusinessException {
        LogSupport.logInfo("补偿扣减库存, compensate, productId:{}, count:{}", productId, count);
        getBaseMapper().compensateDecrease(productId, count);

        return true;
    }
}
